<?php

namespace App\Http\Controllers\Business;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Http\Controllers\Controller;
use App\Models\Business\ShiftSetting;
use Illuminate\Http\Request;

class ShiftSettingController extends Controller
{
    use ModelSearchTrait;

    //
    public function index(Request $request, ShiftSetting $shiftSetting)
    {
        $shiftSetting=$this->singleModelSearch($request,$shiftSetting,$this->shiftCondition());
        $settings=$shiftSetting->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success($settings);
    }

    //
    public function shiftCondition()
    {
        return [
            ['shift_name','like'],
        ];
    }

    //
    public function store(Request $request)
    {
        if(!$request->filled('shift_name')){
            return $this->failed('班次名称不能为空',201);
        }
        $data=$this->getShiftData($request);
        ShiftSetting::create($data);
        return $this->success(['msg'=>'添加成功']);
    }

    //
    public function getShiftData($request){
        return [
            'shift_name'=>mb_substr($request->shift_name,0,64),
            'head_on_off_time'=>$request->head_on_off_time??null,
            'branch_on_off_time'=>$request->branch_on_off_time??null,
        ];
    }

    //
    public function show(Request $request)
    {
        $show=ShiftSetting::find($request->shift_id??0);
        return $this->success($show);
    }

    //
    public function update(Request $request, ShiftSetting $shiftSetting)
    {
        if(!$request->filled('shift_name')){
            return $this->failed('班次名称不能为空',201);
        }
        $shift=$shiftSetting->find($request->shift_id??0);
        if(empty($shift)){
            return $this->failed('id错误，无此设置',201);
        }
        $data=$this->getShiftData($request);
        $shift->update($data);
        return $this->success(['msg'=>'编辑成功']);
    }

    //
    public function destroy(Request $request, ShiftSetting $shiftSetting)
    {
        $shift=$shiftSetting->find($request->shift_id??0);
        if(empty($shift)){
            return $this->failed('id错误，无此类型',201);
        }
        $shift->delete();
        return $this->success(['msg'=>'删除成功']);
    }

    //
    public function getAllShifts(){
        $shifts=ShiftSetting::all();
        return $this->success($shifts);
    }

}
